package jmars.mobile.worker;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import jmars.mobile.common.Investigator;
import jmars.mobile.common.PropertiesLoader;
import jmars.mobile.common.Sha;
import jmars.mobile.datainvestigation.Summary;

/**
 * 
 * 
 * @author Jan
 *
 */
public class TimeSequenceV2 implements Investigator {

	@SuppressWarnings("deprecation")
	@Override
	public Long compute(File[] files, FileWriter writer) throws IOException, ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(Summary.dateFormat);
		Date begin=null;
		if(PropertiesLoader.getProperty("time.beginDate")!=null&&!"".equals(PropertiesLoader.getProperty("time.beginDate")))
			begin= sdf.parse(PropertiesLoader.getProperty("time.beginDate"));
		Date end=null;
		if(PropertiesLoader.getProperty("time.endDate")!=null&&!"".equals(PropertiesLoader.getProperty("time.endDate")))
			end= sdf.parse(PropertiesLoader.getProperty("time.endDate"));
		Long interval = Long.parseLong(PropertiesLoader.getProperty("time.intervalMinutes"))*60000;
		
		Long total = 0L,min=0L,max=0L;
		FileInputStream fis;
		BufferedReader reader;
		String row;
		String[] cols;
		Map<Long,Map<String,Long>> results=new HashMap<Long,Map<String,Long>>();
		DecimalFormat df = new DecimalFormat();
		df.applyPattern("0");
		Date tempBegin,tempEnd;
		Long tempBL,tempEL;
		Long segBL,segEL;
		String groupKey;
		boolean groupFlag=(Summary.groupColumns!=null&&!"".equals(Summary.groupColumns));
		for(File inputFile:files){
			fis = new FileInputStream(inputFile);
			reader = new BufferedReader(new InputStreamReader(fis));
			while((row=reader.readLine())!=null){
				cols=row.split(Summary.columnSeperator);
				if(Summary.filterRow(cols,true,false)) continue;
				
				groupKey="";
				if(groupFlag)
					for(Integer idx:Summary.groupColumnIdx)
						if(idx<cols.length)
							groupKey=groupKey+"$_$"+cols[idx]+"$_$";
						else groupKey=groupKey+"$_$$_$";
				try{
					tempBegin=sdf.parse(cols[5]);
					tempEnd=sdf.parse(cols[6]);
				}catch(Exception e){
					continue;
				}
				if(tempBegin.getYear()!=112||tempEnd.getYear()!=112)continue;
				tempBL=0L;tempEL=0L;segBL=0L;segEL=0L;

				if(begin!=null&&tempBegin.getTime()<begin.getTime())
					tempBL=begin.getTime();
				else
					tempBL=tempBegin.getTime();
				if(end==null||tempEnd.getTime()<end.getTime())
					tempEL=tempEnd.getTime();
				else
					tempEL=end.getTime();
				if(tempEL<tempBL)
					continue;
				for(Long ll=tempBL-tempBL%interval;ll<=tempEL-tempEL%interval;ll=ll+interval){
					if(tempBL<ll) segBL=ll;
					else segBL=tempBL;
					if(ll+interval<tempEL) segEL=ll+interval;
					else segEL=tempEL;
					if(ll<min)min=ll;
					if(ll>max)max=ll;
					if(!results.containsKey(ll))results.put(ll, new HashMap<String,Long>());
					if(tempBL.equals(tempEL)){
						if(results.get(ll).containsKey(groupKey))
							results.get(ll).put(groupKey, results.get(ll).get(groupKey)+Long.parseLong(cols[10]));
						else{
							results.get(ll).put(groupKey, Long.parseLong(cols[10]));
						}
					}else{
						if(results.get(ll).containsKey(groupKey))
							results.get(ll).put(groupKey, results.get(ll).get(groupKey)+Long.parseLong(cols[10])*
									(segEL-segBL)/(tempEnd.getTime()-tempBegin.getTime()));
						else{
							results.get(ll).put(groupKey, Long.parseLong(cols[10])*(segEL-segBL)/(tempEnd.getTime()-tempBegin.getTime()));
						}
					}

				}
				total++;
			}
			reader.close();
			fis.close();
			System.out.println(inputFile.getName()+" finished at "+total);
		}
		writer.write("%total:"+df.format(total)+"\r\n");
		writer.write("%temporal count:"+results.size()+"\r\n");
		writer.write("%begin: "+sdf.format(min)+"\r\n");
		writer.write("%end: "+sdf.format(max)+"\r\n");
		writer.write("%*****************details******************\r\n");
		writer.write("%time");
		for(Integer idx:Summary.groupColumnIdx){
			writer.write(","+(idx==null?"":Summary.columns[idx]));
		}
		writer.write(",traffic\r\n");
		for(Long l=min;l<=max;l=l+interval){
			if(results.containsKey(l))
			for(String gkey:results.get(l).keySet()){
				writer.write(df.format(l)+
						(gkey.equals("")?"":Sha.digest32HexSHA1(gkey))
						+","+df.format(results.get(l).get(gkey))+"\r\n");
//				writer.write(df.format(l)+","+Sha.convertToHex(gkey.getBytes())
//						+","+df.format(results.get(l).get(gkey))+"\r\n");
			}
		}
	        
		return total;
	}

}
